<script>

import {
  getCategoryOptions,
  keyWordUsageRecordList,
  removeKeyWordUsage
} from "@/views/manage/keyWord/api";
import { formatPercentage, isNull } from "@/utils/service";
import FeatureTemplate from "@/views/manage/keyWord/component/featureTemplate.vue";
import CopyKeyWordBtn from "@/views/manage/keyWord/component/copyKeyWordBtn.vue";
import { getOptions as getGroupOptions, groupIdToGroupName } from "@/views/manage/keyWord/component/groupApi";
import KeyWordGroup from "@/views/manage/keyWord/component/keyWordGroup.vue";

export default {
  name: "appendZtc",
  components: { KeyWordGroup, CopyKeyWordBtn, FeatureTemplate },
  computed: {
    pageData() {
      const start = (this.page.current - 1) * this.page.size;
      const end = start + this.page.size;
      return this.keyWordList.slice(start, end);
    }
  },
  data() {
    return {
      /* 选中的品类*/
      selectCategory: "",
      /*品类选项*/
      categoryOptions: [],
      /* 所有分组选项*/
      allGroupOptions: [],
      /* 分组选项*/
      groupOptions: [],
      /* 选中的分组id */
      groupSelectId: [],
      /* 选项加载*/
      groupSelectLoading: true,
      /*关键词列表*/
      keyWordList: [],
      /*分页对象*/
      page: {
        selectRow: [],
        loading: false,
        size: 10,
        current: 1
      },
      ztc: {
        account: "",
        password: "",
        percent: 60,
        priceCap: 1.00,
        matchesType: "精准匹配"
      },
      drawer: false,
      direction: "rtl"
    };
  },
  mounted() {
    let _ = this;
    getCategoryOptions(_, "categoryOptions");
    getGroupOptions(_,null,r=> {
      _.allGroupOptions = r
      _.groupOptions = r
    },f=>{})
  },
  methods: {
    isNull,
    getKeyWordUsageRecordList(){
      let _ = this;
      keyWordUsageRecordList(_, _.selectCategory,_.groupSelectId, "IS_APPEND_ZTC", res => {
        _.keyWordList = res;
      });
    },
    defTemplate(){
      this.ztc.account = "";
      this.ztc.password = "";
      this.ztc.percent = 60;
      this.ztc.priceCap =  1.00;
      this.ztc.matchesType = "精准匹配";
    },
    loadTemplate(params){
      this.ztc = params
    },
    checkParam(){
      if (isNull(this.ztc.account)){
        this.$message.warning("请输入账号")
        return false
      }
      if (isNull(this.ztc.password)){
        this.$message.warning("请输入密码")
        return false
      }
      return true;
    },
    selectCategoryChange(v) {
      if (isNull(v)) {
        return;
      }
      this.getKeyWordUsageRecordList()
    },
    selectGroupChange(v){
      if (isNull(v)) {
        this.groupSelectId = null;
      }
      this.getKeyWordUsageRecordList();
    },
    tableSelectChange(v) {
      this.page.selectRow = v;
    },
    tableSortChange(column, prop, order) {
      if (!isNull(column.order)) {
        if (column.order.startsWith("asc")) {
          this.keyWordList.sort((a, b) => a[column.prop] - b[column.prop]);
        } else {
          this.keyWordList.sort((a, b) => b[column.prop] - a[column.prop]);
        }
      } else {
        this.keyWordList.sort((a, b) => b["searchPeopleNum"] - a["searchPeopleNum"]);
      }
    },
    delTableRow(delRows) {
      let _ = this;
      if (delRows.length === 0) {
        this.$message.warning("没有选择删除目标");
        return;
      }
      _.page.loading = true;
      removeKeyWordUsage(this, JSON.stringify(delRows.map(i => i.id)), "IS_APPEND_ZTC",
        data => {
          _.$message.success("提交成功");
          _.selectCategoryChange(_.selectCategory);
        }, res => {
          _.page.loading = false;
        });
    },
    submit() {
      alert("ok");
      console.log("data:", this.ztc);
    },
    pageSizeChange(v) {
      this.page.size = v;
    },
    pageCurrentChange(v) {
      this.page.current = v;
    },
    /** 将表格值转为百分比*/
    valueToPercentage(row, column, cellValue, index) {
      return formatPercentage(cellValue);
    },
    /** 表格值保留两位小数*/
    percentageWithFixedDigits2(row, column, cellValue, index) {
      return cellValue ? cellValue.toFixed(2) : "-";
    },
    /** 表格值保留三位小数*/
    percentageWithFixedDigits4(row, column, cellValue, index) {
      return cellValue ? cellValue.toFixed(4) : "-";
    },
    groupIdFormatName(row, column, cellValue, index){
      return groupIdToGroupName(cellValue,this.allGroupOptions)
    },
    groupSelectVisibleChange(v){
      let _ = this;
      _.groupSelectLoading = true;
      if (v){
        getGroupOptions(_,null,r=> {
          _.allGroupOptions = r;
          _.groupOptions = r.filter(i => i.categoryName === _.selectCategory || i.id === 0);
        },f => {
          _.groupSelectLoading = false
        })
      }
    }
  }
};
</script>

<template>
  <div style="margin: 10px 0">
    <!-- 头部内容  -->
    <div class="header">
      <div>
        <el-select
          @change="selectCategoryChange"
          style="width: 230px"
          size="mini" v-model="selectCategory" clearable filterable placeholder="请筛选品类">
          <el-option
            v-for="item in categoryOptions"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
        </el-select>

        <el-select
          v-if="!isNull(selectCategory)"
          @change="selectGroupChange"
          @visible-change="groupSelectVisibleChange"
          :loading="groupSelectLoading"
          loading-text="加载中...."
          style="width: 230px;margin-left: 5px;"
          size="mini" v-model="groupSelectId" clearable filterable placeholder="请选择分组">
          <el-option
            v-for="item in groupOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>

        <div style="margin-top: 5px">

          <key-word-group
            @updateTable="getKeyWordUsageRecordList"
            :select-row=page.selectRow
            :group-options=groupOptions
            :show-edit="true"
            style="margin-right: 5px;"
          >
          </key-word-group>

          <el-popconfirm
            style="margin-right: 5px;"
            confirm-button-text="是的"
            cancel-button-text="不用了"
            icon="el-icon-info"
            icon-color="red"
            title="确定要移除选中项吗？"
            @confirm="delTableRow(page.selectRow)"
          >
            <el-button
              slot="reference"
              v-show="keyWordList.length > 0"
              :disabled="page.selectRow.length === 0"
              type="danger"
              size="mini"
            >
              移除选中项
            </el-button>
          </el-popconfirm>

          <copy-key-word-btn
            style="margin-right: 5px;"
            :select-row="page.selectRow"
            :show="keyWordList.length > 0"
          >
          </copy-key-word-btn>

          <el-button
            v-show="keyWordList.length > 0"
            size="mini"
            type="primary"
            @click="drawer = true"
          >
            追加到直通车
          </el-button>
        </div>
      </div>
    </div>

    <div class="main">
      <div>
        <el-table
          @selection-change="tableSelectChange"
          v-loading="page.loading"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.8)"
          style="width: 100%"
          height="73vh"
          :row-style="{height:'20px'}"
          :cell-style="{padding:'0px'}"
          border
          :data="pageData"
          @sort-change="tableSortChange"
        >
          <el-table-column fixed="left" align="center" type="selection" width="40" />
          <el-table-column fixed="left" align="center" :show-overflow-tooltip=true prop="name" label="关键词"
                           width="200" />
          <el-table-column fixed="left" align="center" :show-overflow-tooltip=true prop="groupId" label="组名"
                           :formatter="groupIdFormatName"
                           width="200">
          </el-table-column>
          <el-table-column align="center" prop="adId" label="操作人编号" width="100" />
          <el-table-column prop="searchPeopleNum" sortable label="搜索人数" align="center" width="110" />
          <el-table-column prop="searchCount" sortable label="搜索次数" align="center" width="110" />
          <el-table-column prop="clickRate" sortable label="点击率" width="100" align="center"
                           :formatter="valueToPercentage" />
          <el-table-column prop="clickPeopleNum" sortable label="点击人数" align="center" width="110" />
          <el-table-column prop="clickCount" sortable label="点击次数" align="center" width="110" />
          <el-table-column prop="transactionAmount" sortable label="交易金额" align="center" width="110"
                           :formatter="percentageWithFixedDigits2" />
          <el-table-column prop="paymentConversionRate" sortable label="ROI" align="center" width="110"
                           :formatter="valueToPercentage" />
          <el-table-column prop="onlineGoodsNum" align="center" sortable label="在线商品数" width="120" />
          <el-table-column prop="mallClickRate" align="center" sortable label="商城点击比例" width="130"
                           :formatter="valueToPercentage" />
          <el-table-column prop="ztcReferencePrice" align="center" sortable label="直通车参考价" width="130"
                           :formatter="percentageWithFixedDigits2" />
          <el-table-column prop="paymentPeopleNum" align="center" sortable label="支付人数" width="110" />
          <el-table-column prop="unitPrice" sortable align="center" label="客单价" width="100"
                           :formatter="percentageWithFixedDigits2" />
          <el-table-column prop="searchUsersPerGoods" align="center" sortable label="搜索人数/在线商品数" width="180"
                           :formatter="percentageWithFixedDigits4" />
          <el-table-column prop="transactionAmountPerGoods" align="center" sortable label="交易金额/在线商品数"
                           width="180"
                           :formatter="percentageWithFixedDigits4" />
          <el-table-column prop="visitorAverageValue" align="center" sortable label="访客平均价值" width="130"
                           :formatter="percentageWithFixedDigits2" />
          <el-table-column prop="goodsAverageValue" align="center" sortable label="商品平均价值" width="130"
                           :formatter="percentageWithFixedDigits4" />
          <el-table-column prop="visitorCompetitionIndex" align="center" label="商品访客竞争度" width="120"
                           :formatter="percentageWithFixedDigits2" />
          <el-table-column prop="highQualityValueWords" align="center" sortable label="优质价值词" width="120" />
          <el-table-column prop="competitionDegree" align="center" sortable label="竞争度" width="120"
                           :formatter="percentageWithFixedDigits4" />
          <el-table-column prop="estimatedConversionQuantity" align="center" sortable label="预估转化件数" width="130"
                           :formatter="percentageWithFixedDigits2" />
          <el-table-column prop="averageTransactionIndex" align="center" sortable label="平均交易指数" width="130"
                           :formatter="percentageWithFixedDigits2" />
          <el-table-column align="center" prop="createTime" label="创建时间" width="200" />
          <el-table-column align="center" prop="updateTime" label="修改时间" width="200" />
          <el-table-column fixed="right" align="center" prop="updateTime" label="操作" width="80">
            <template slot-scope="{row}">
              <div style="margin:5px">
                <el-button size="mini" type="danger" @click="delTableRow([row])">移除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div class="footer">
      <div>
        <el-pagination
          @size-change="pageSizeChange"
          @current-change="pageCurrentChange"
          :current-page="page.current"
          :page-sizes="[10,50,100, 200, 300,500,1000]"
          :page-size=page.size
          layout="total, sizes, prev, pager, next, jumper"
          :total=keyWordList.length>
        </el-pagination>
      </div>
      <div>
        <span class="label">选中数据量 : </span>
        <span style="font-weight: bold">{{ page.selectRow.length }}</span>
      </div>
    </div>

    <el-drawer
      title="追加到直通车"
      :visible.sync="drawer"
      :direction="direction">
      <div>
        <div style="height: 86.5vh;">
          <FeatureTemplate
            type="APPEND_TO_ATC"
            :task-params="ztc"
            :def-template="defTemplate"
            :load-template="loadTemplate"
            :check-param="checkParam"
          >
          </FeatureTemplate>
          <div>
            <div style="margin-left: 30px;">
              <span class="label">按市场出价百分比 :  </span>
              <el-input-number v-model="ztc.percent" :min="1" :step="1" size="medium"></el-input-number>
            </div>
            <div style="margin: 5px 30px;">
              <span class="label">最高出价 :  </span>
              <el-input-number style="margin-left: 59px;" v-model="ztc.priceCap" :min="0.05" :step="0.01" size="medium"
                               :precision="2"></el-input-number>
            </div>
            <div style="margin: 5px 30px;">
              <span class="label">新关键词匹配类型 :  </span>
              <el-radio-group v-model="ztc.matchesType" size="medium">
                <el-radio-button label="广泛匹配">广泛</el-radio-button>
                <el-radio-button label="精准匹配">精准</el-radio-button>
              </el-radio-group>
            </div>
            <div style="margin: 0 10px;">
              <el-divider content-position="center">账号&密码</el-divider>
              <el-row justify="center">
                <el-col :span="24" style="display: flex; justify-content: center;">
                  <span class="label">账号:</span>
                  <el-input style="width:85%;margin-left: 10px" v-model="ztc.account" placeholder="淘宝或其他账号"
                            size="medium"></el-input>
                </el-col>
              </el-row>
              <el-row justify="center" style="margin-top: 5px;">
                <el-col :span="24" style="display: flex; justify-content: center;">
                  <span class="label">密码:</span>
                  <el-input style="width:85%;margin-left: 10px" v-model="ztc.password" placeholder="淘宝或其他密码"
                            show-password size="medium"></el-input>
                </el-col>
              </el-row>
            </div>
          </div>
        </div>
      </div>
      <div style="text-align: center">
        <el-button style="width: 98%" type="success">发布自动任务</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<style scoped>
.header {

}

.main {
  margin: 10px 0;
}

.footer {
  display: flex;
  justify-content: space-between;
}

.label {
  color: #57606f;
  font-size: 14px;
  font-weight: bold;
  letter-spacing: 0.05em;
}
</style>